
package com.jf.cloud.service.sysmanager.remote;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.jf.cloud.service.sysmanager.common.base.AjaxPageData;
import com.jf.cloud.service.sysmanager.common.base.OPaging;
import com.jf.cloud.service.sysmanager.common.db.Query;
import com.jf.cloud.service.sysmanager.common.util.DateUtil;
import com.jf.cloud.service.sysmanager.common.util.RandomUtil;
import com.jf.cloud.service.sysmanager.common.util.RegexValidUtil;
import com.jf.cloud.service.sysmanager.common.util.StringUtil;
import com.jf.cloud.service.sysmanager.constant.PubgConstant;
import com.jf.cloud.service.sysmanager.constant.TradeType;
import com.jf.cloud.service.sysmanager.dao.IPubgClubService;
import com.jf.cloud.service.sysmanager.dao.IPubgFinanceFlowDetailService;
import com.jf.cloud.service.sysmanager.dao.IPubgOperateLogService;
import com.jf.cloud.service.sysmanager.dao.IPubgTeamService;
import com.jf.cloud.service.sysmanager.entity.PubgClub;
import com.jf.cloud.service.sysmanager.entity.PubgFinanceFlowDetail;
import com.jf.cloud.service.sysmanager.entity.PubgOperateLog;
import com.jf.cloud.service.sysmanager.entity.PubgTeam;
import com.jf.cloud.service.sysmanager.entity.SysStaff;
import com.jf.cloud.service.sysmanager.support.entity.Result;
import com.jf.cloud.service.sysmanager.support.web.BaseController;

/**
 * 员工控制器
 * 
 * @author 代码机1.0 创建时间：2018-03-31
 */
@Controller
@RequestMapping("/pubgClub")
public class PubgClubController extends BaseController {

	/**
	 * 日志
	 */
	private static Log log = LogFactory.getLog(PubgClubController.class);

	/**
	 * 员工服务
	 */
	@Resource
	private IPubgClubService pubgClubService;

	@Resource
	private IPubgTeamService pubgTeamService;

	@Resource
	private IPubgFinanceFlowDetailService pubgFinanceFlowDetailService;

	@Resource
	private IPubgOperateLogService pubgOperateLogService;

	/**
	 * 获取俱乐部列表
	 *
	 * @author 高冬冬 2018年3月31日
	 */
	@RequestMapping("/list")
	public String list(HttpServletRequest request) {
		return "jsp/pubg/pubgClub_list";
	}

	/**
	 * 获取俱乐部列表
	 *
	 * @author 高冬冬 2018年3月31日
	 */
	@ResponseBody
	@RequestMapping("/pubgClub.json")
	public AjaxPageData<PubgClub> list(HttpServletRequest request, OPaging<PubgClub> page) {
		return getAjaxPageData(pubgClubService.findPage(page));
	}

	/**
	 * 俱乐部编辑
	 *
	 * @author 高冬冬 2018年3月31日
	 */
	@RequestMapping("/pubgClubEditer")
	public String pubgClubEditer(HttpServletRequest request,HttpServletResponse response) {
		Long id = getLongValue(request, "rowId");
		PubgClub pubgClub = new PubgClub();
		if (id != null && id > 0) {
			pubgClub = pubgClubService.findByPK(id);
		}else {
			String inviteCode = RandomUtil.getRandomLeterAndNumber(6);
			pubgClub.setInviteCode(inviteCode);
			pubgClub.setExchageRatio("1:1");
		}
		request.setAttribute("pubgClub", pubgClub);
		return "jsp/pubg/pubgClub_editer";
	}

	/**
	 * 加鸡蛋跳转
	 *
	 * @author 高冬冬 2018年4月2日
	 */
	@RequestMapping("/toAddEgg")
	public String toAddEgg(HttpServletRequest request,HttpServletResponse response) {
		Long rowId = getLongValue(request, "rowId");
		String opera = getStringValue(request, "opera");//加/减鸡蛋操作
		PubgClub pubgClub = new PubgClub();
		if (rowId != null && rowId > 0) {
			pubgClub = pubgClubService.findByPK(rowId);
		}
		request.setAttribute("pubgClub", pubgClub);
		request.setAttribute("opera", opera);
		return "jsp/pubg/pubgClub_addEgg";
	}

	/**
	 * 加/减鸡蛋
	 * 注意此处传递的值是变化的鸡蛋数量，不是总量！！！
	 * @author 高冬冬 2018年3月31日
	 */
	@RequestMapping("/addOrReduceEgg")
	public String addOrReduceEgg(HttpServletRequest request, PubgClub pubgClub) {
		String opera = getStringValue(request, "opera");
		String returnView = list(request);
		if (isReCommit(request)) {
			return returnView;
		}
		request.setAttribute("code", 1);
		try {
			if (pubgClub.getRowId() == null || pubgClub.getRowId() <= 0) {
				request.setAttribute("msg", "处理失败!");
				return returnView;
			}
			SysStaff user = getLoginUser(request);
			if (user == null) {
				return "/";
			}
			
			if (pubgClub.getClubBalance() == null) {
				request.setAttribute("msg", "鸡蛋数量不能为空!");
				return returnView;
			}
			if (pubgClub.getClubBalance() < 0) {
				request.setAttribute("msg", "鸡蛋数量不能为负数!");
				return returnView;
			}
			if (pubgClub.getClubBalance() > 1000000) {
				request.setAttribute("msg", "鸡蛋数量不能大于100W!");
				return returnView;
			}
			if ("reduce".equals(opera)) {//减鸡蛋操作处理数据
				pubgClub.setClubBalance(0 - pubgClub.getClubBalance());
			}
			Double sumEgg = pubgClub.getClubBalance();//变化鸡蛋后的总和
			PubgClub oldPubgClub = pubgClubService.findByPK(pubgClub.getRowId());//原数据
			if (oldPubgClub.getClubBalance() != null && oldPubgClub.getClubBalance() >= 0) {
				sumEgg = pubgClub.getClubBalance() + oldPubgClub.getClubBalance();
			}
			if (sumEgg < 0) {
				request.setAttribute("msg", "俱乐部余额不能为负数!");
			}
			//加鸡蛋时记录到充值总额,注意此处传递的值是变化的鸡蛋数量，不是总量！！！
			if (pubgClub.getClubBalance() > 0) {
				pubgClub.setRechargeSum(pubgClub.getClubBalance());
			}
			pubgClub.setOptId(user.getRowId());
			pubgClub.setOptAccount(user.getStaffAccount());
			pubgClub.setOptTime(DateUtil.getCurrentDateTime());
			this.pubgClubService.updatePubgClub(pubgClub);
			if ("add".equals(opera)) {
				request.setAttribute("msg", "加鸡蛋成功!");
			} else if ("reduce".equals(opera)) {
				request.setAttribute("msg", "减鸡蛋成功!");
			}
			//记录资金流水
			PubgClub newPubgClub = pubgClubService.findByPK(pubgClub.getRowId());
			PubgFinanceFlowDetail pubgFinanceFlowDetail = new PubgFinanceFlowDetail();
			if (pubgClub.getClubBalance() >= 0) {
				pubgFinanceFlowDetail.setTradeTypeId(TradeType.EGG_ADD.key());
				pubgFinanceFlowDetail.setTradeTypeName(TradeType.EGG_ADD.value());
				pubgFinanceFlowDetail.setInOutFlag(PubgConstant.FINANCE_FLOW_IN);
			} else {
				pubgFinanceFlowDetail.setTradeTypeId(TradeType.EGG_REDUCE.key());
				pubgFinanceFlowDetail.setTradeTypeName(TradeType.EGG_REDUCE.value());
				pubgFinanceFlowDetail.setInOutFlag(PubgConstant.FINANCE_FLOW_OUT);
			}
			pubgFinanceFlowDetail.setClubId(newPubgClub.getRowId());
			pubgFinanceFlowDetail.setClubName(newPubgClub.getClubName());
			pubgFinanceFlowDetail.setCreateTime(DateUtil.getCurrentDateTime());
			pubgFinanceFlowDetail.setTradeMoney(Math.abs(pubgClub.getClubBalance()));//客户端传递的变化鸡蛋数量
			pubgFinanceFlowDetail.setTradeMoneyAfter(newPubgClub.getClubBalance());//更新后的鸡蛋数量
			pubgFinanceFlowDetailService.saveOrUpdatePubgFinanceFlowDetail(pubgFinanceFlowDetail);
			
			//记录操作日志
			PubgOperateLog pubgOperateLog = new PubgOperateLog();
			pubgOperateLog.setClubId(newPubgClub.getRowId());
			pubgOperateLog.setClubName(newPubgClub.getClubName());
			if (pubgClub.getClubBalance() >= 0) {//客户端传递的变化鸡蛋数量
				pubgOperateLog.setOptType(TradeType.EGG_ADD.key());
				String content = "对'" + newPubgClub.getClubName() + "'进行加鸡蛋操作，操作人：" + user.getStaffAccount();
				pubgOperateLog.setContent(content);
			}else {
				String content = "对'" + newPubgClub.getClubName() + "'进行减鸡蛋操作，操作人：" + user.getStaffAccount();
				pubgOperateLog.setOptType(TradeType.EGG_REDUCE.key());
				pubgOperateLog.setContent(content);
			}
			pubgOperateLog.setOptId(user.getRowId());
			pubgOperateLog.setOptName(user.getStaffAccount());
			pubgOperateLog.setOptTime(DateUtil.getCurrentDateTime());
			pubgOperateLogService.saveOrUpdatePubgOperateLog(pubgOperateLog);
		} catch (Exception e) {
			log.error("addOrReduceEgg ---------> has error",e);
			if ("add".equals(opera)) {
				request.setAttribute("msg", "加鸡蛋失败,未知错误!");
			} else if ("reduce".equals(opera)) {
				request.setAttribute("msg", "减鸡蛋失败,未知错误!");
			}
			return returnView;
		}
		return returnView;
	}

	/**
	 * 添加/编辑俱乐部
	 *
	 * @author 高冬冬 2018年3月31日
	 */
	@RequestMapping("/savePubgClub")
	public String savePubgClub(HttpServletRequest request, PubgClub pubgClub) {
		String returnView = list(request);
		if (isReCommit(request)) {
			return returnView;
		}
		request.setAttribute("code", 1);
		try {
			SysStaff user = getLoginUser(request);
			if (user == null) {
				return "/";
			}
			
			if (StringUtil.isEmpty(pubgClub.getClubName())) {
				request.setAttribute("msg", "俱乐部名称不能为空!");
				return returnView;
			}
			if (pubgClub.getClubName().length() > 20) {
				request.setAttribute("msg", "俱乐部名称最多输入20个字符!");
				return returnView;
			}
			if (StringUtil.isEmpty(pubgClub.getMinisterName())) {
				request.setAttribute("msg", "管理员不能为空!");
				return returnView;
			}
			if (StringUtil.isEmpty(pubgClub.getClubIntro())) {
				request.setAttribute("msg", "介绍不能为空!");
				return returnView;
			}
			if (pubgClub.getClubIntro().length() > 200) {
				request.setAttribute("msg", "介绍不能超过200个字!");
				return returnView;
			}
			if (StringUtil.isEmpty(pubgClub.getInviteCode())) {
				request.setAttribute("msg", "邀请码不能为空!");
				return returnView;
			}
			if (pubgClub.getInviteCode().length() != 6) {
				request.setAttribute("msg", "邀请码长度只能为6个字符!");
				return returnView;
			}
			if (!RegexValidUtil.compile(RegexValidUtil.invitecode, pubgClub.getInviteCode())) {
				request.setAttribute("msg", "邀请码只能包含字母和数字!");
				return returnView;
			}
			if (StringUtil.isEmpty(pubgClub.getExchageRatio())) {
				request.setAttribute("msg", "兑换比例不能为空!");
				return returnView;
			}

			pubgClub.setOptId(user.getRowId());
			pubgClub.setOptAccount(user.getStaffAccount());
			pubgClub.setOptTime(DateUtil.getCurrentDateTime());
			if (pubgClub.getRowId() == null || pubgClub.getRowId() == 0) {
				//TODO 兑换比例先写死为 1:1
				pubgClub.setExchageRatio("1:1");
				pubgClub.setClubBalance(0d);
				pubgClub.setRechargeSum(0d);
				this.pubgClubService.saveOrUpdatePubgClub(pubgClub);
				request.setAttribute("msg", "添加俱乐部成功!");
				log.info(user.getStaffAccount() + " 添加俱乐部");

			} else {
				this.pubgClubService.updatePubgClub(pubgClub);
				request.setAttribute("msg", "修改俱乐部成功!");
				log.info(user.getStaffAccount() + " 修改俱乐部");

			}
		} catch (Exception e) {
			log.error("savePubgClub ---------> has error",e);
			request.setAttribute("msg", "保存俱乐部失败,未知错误!");
			return returnView;
		}
		return returnView;
	}

	/**
	 * 验证邀请码是否唯一
	 *
	 * @author 高冬冬 2018年3月31日
	 */
	@ResponseBody
	@RequestMapping("/checkInviteCode")
	public Map<String, Object> checkInviteCode(HttpServletRequest request, Long rowId, String inviteCode) {
		Map<String, Object> result = new HashMap<String, Object>();
		result.put("code", "-1");
		try {
			if (StringUtil.isNotEmpty(inviteCode)) {
				Query query = new Query();
				query.put("_NOT_EQUAL$ROW_ID", rowId);
				query.put("INVITE_CODE", inviteCode);
				if (inviteCode.length() != 6) {
					result.put("code", "-2");
					result.put("message", "邀请码长度只能为6个字符！");
					return result;
				}
				List<PubgClub> clubList = pubgClubService.findList(query);
				if (clubList != null && clubList.size() > 0) {
					result.put("code", "-2");
					result.put("message", "邀请码已存在！");
					return result;
				}
				query = new Query();
				query.put("INVITE_CODE", inviteCode);
				List<PubgTeam> teamList = pubgTeamService.findList(query);
				if (teamList != null && teamList.size() > 0) {
					result.put("code", "-2");
					result.put("message", "邀请码已存在！");
					return result;
				}
			}
			result.put("code", "0");
		} catch (Exception e) {
			e.printStackTrace();
		}
		return result;
	}
	
	/**
	 * 检查俱乐部靓号是否存在
	 * 
	 * @author 朱建文 创建时间：2018年5月8日 下午4:22:33
	 */
	@ResponseBody
	@RequestMapping("/checkClubNoIsExist")
	public Result<String> checkClubNoIsExist(Long rowId, String clubNo, HttpServletRequest request){
		Result<String> result = new Result<String>();
		result.setCode(-1);
		result.setMessage("检查俱乐部靓号唯一性失败！");
		
		try {
			SysStaff sysStaff = getLoginUser(request);
			if (sysStaff == null) {
				result.setCode(-2);
				result.setMessage("请重新登陆！");
			}
			boolean boo = this.pubgClubService.checkClubNoIsExist(rowId, clubNo);
			if (boo) {
				result.setCode(1);
				result.setMessage("该靓号已存在！");
			} else {
				result.setCode(0);
				result.setMessage("该靓号可以使用！");
			}
		} catch (Exception e) {
			log.error("检查俱乐部靓号是否存在出错！", e);
		}
		return result;
	}
}
